package com.whoami.dataplatform.tag_combine;

import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.LazyOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileAsBinaryOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.orc.mapred.OrcList;
import org.apache.orc.mapred.OrcStruct;
import org.apache.orc.mapreduce.OrcInputFormat;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.BitSet;
import java.util.Properties;

/**
 * 给所有被打上标签的设备id编号, 方便下一步转为bitmap
 * <p>
 * 输入
 * /user/mz_supertool/datalake/src/segment/dwd_segment/20190723/data
 * 000Lh0rMaC79  [{"id":"23","name":"休闲娱乐"},{"id":"32","name":"视频/短视频"}]
 *
 * @author tzp
 * @since 2019/7/31
 */
@SuppressWarnings("Duplicates")
public class UIDToNumberJob1 extends Configured implements Tool {
    /**
     * 给MR框架的一堆配置, 文件里面的内容会被set到mr conf里
     */
    public static final String PARAMS_MR_PROP = "mr_properties";

    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        String mrProFile = conf.get(PARAMS_MR_PROP);
        if (StringUtils.isNotEmpty(mrProFile)) {
            Properties mrProperties = new Properties();
            mrProperties.load(new FileInputStream(mrProFile));
            for (Object key : mrProperties.keySet()) {
                conf.set(key.toString(), mrProperties.get(key).toString());
            }
        }
        String date = args[0];//20190723
        String input = args[1];
        String output = args[2];//outputbase

        Job job = Job.getInstance(conf, this.getClass().getSimpleName() + " " + date);
        job.setJarByClass(this.getClass());

        //输入
        job.setInputFormatClass(OrcInputFormat.class);
        FileInputFormat.addInputPath(job, new Path(input));

        //mapper
        job.setMapperClass(ReverseMapper.class);
        job.setMapOutputKeyClass(BytesWritable.class);
        job.setMapOutputValueClass(Text.class);

        //reducer
        job.setReducerClass(CountReducer.class);
        job.setNumReduceTasks(32);

        //输出
        job.setOutputFormatClass(LazyOutputFormat.class);
        job.setOutputKeyClass(BytesWritable.class);
        job.setOutputValueClass(BytesWritable.class);
        LazyOutputFormat.setOutputFormatClass(job, SequenceFileAsBinaryOutputFormat.class);

        FileOutputFormat.setOutputPath(job, new Path(output));

        boolean result = job.waitForCompletion(true);

        return result ? 0 : 1;
    }

    public static class ReverseMapper extends Mapper<NullWritable, OrcStruct, BytesWritable, Text> {
        private BytesWritable outKey = new BytesWritable();
        private Text outValue = new Text();
        BitSet tidbits = new BitSet(1024);

        @Override
        protected void map(NullWritable ignore, OrcStruct value, Context context) throws IOException, InterruptedException {
            tidbits.clear();
            String uid = value.getFieldValue("uid").toString();

            OrcList<OrcStruct> segments = (OrcList<OrcStruct>) value.getFieldValue("segment");
            segments.stream()
                    .map((x) -> x.getFieldValue("id").toString())
                    .map(Integer::valueOf)
                    .forEach((x) -> tidbits.set(x));

            byte[] tidBytes = tidbits.toByteArray();

            outKey.set(tidBytes, 0, tidBytes.length);
            outValue.set(uid);
            context.write(outKey, outValue);
        }
    }

    @SuppressWarnings("Duplicates")
    public static class CountReducer extends Reducer<BytesWritable, Text, BytesWritable, BytesWritable> {
        byte[] newline = "\n".getBytes(StandardCharsets.UTF_8);
        int num = 0, maxNum = 0;
        BytesWritable outValue = new BytesWritable();

        @Override
        protected void reduce(BytesWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            ByteArrayDataOutput tempBytes = ByteStreams.newDataOutput();
            num = 0;
            for (Text value : values) {
                tempBytes.write(value.getBytes(), 0, value.getLength());
                tempBytes.write(newline);
                num++;
            }
            if (num > maxNum) {
                maxNum = num;
            }
            byte[] bytes = tempBytes.toByteArray();
            ByteBuffer byteBuffer = ByteBuffer.allocate(4 + bytes.length - newline.length);
            byte[] outputBytes = byteBuffer.putInt(num)
                    .put(bytes, 0, bytes.length - newline.length)
                    .array();

//            ByteBuffer byteBuffer = ByteBuffer.allocate(4);
//            byte[] outputBytes = byteBuffer.putInt(num).array();

            outValue.set(outputBytes, 0, outputBytes.length);
            context.write(key, outValue);
        }

        @Override
        protected void cleanup(Context context) throws IOException, InterruptedException {
            context.getCounter("maxNum", String.valueOf(maxNum)).increment(1);
        }
    }

    public static void main(String[] args) throws Exception {
        System.exit(ToolRunner.run(new Configuration(), new UIDToNumberJob1(), args));
    }
}
